<?php
/**
 * Created by PhpStorm
 * User: Kong
 * Date: 2025/9/25
 * Time: 14:57
 */

namespace App\Service\Admin;
use Hyperf\DbConnection\Db;
class AdministratorService
{
    /**
     * 创建管理员.
     * @throws \Throwable
     * @return mixed
     */
    public static function createAdministrator($data)
    {
        try {
            $data = [
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => password_hash($data['password'], PASSWORD_DEFAULT),
                'status' => \App\Model\Administrator::NORMAL_STATUS,
                'mobile' => $data['mobile'],
                'gender' => $data['gender']??0,
                'introduction' => $data['introduction']??'',
            ];
            Db::beginTransaction();
            // 查找是否存在邮箱的 admin
            $result = \App\Model\Administrator::query()->where('email', $data['email'])->first();
            if ($result) {
                throw new \Exception('此邮箱已被占用');
            }
            // 添加管理员
            $administrator = \App\Model\Administrator::create($data);
            // 设置用户角色
            $rolesId = $data['roles_id']??[];
            if (count($rolesId) > 0) {
                self::setAdminRole($administrator->id, array_values($rolesId));
            }
            Db::commit();
            return $administrator;
        } catch (\Throwable $exception) {
            Db::rollBack();
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 设置管理员的角色.
     * @throws \Exception
     * @return mixed
     */
    public static function setAdminRole(int $administratorId, array $rolesId)
    {
        $admin = \App\Model\Administrator::query()->find($administratorId);
        if (! $admin) {
            throw new \Exception('未找到管理员用户');
        }

        // 先删除用户的所有角色
        \App\Model\AdministratorRole::query()
            ->where('administrator_id', $administratorId)
            ->delete();

        $roles = \App\Model\Role::query()->find($rolesId);
        if ($roles->count() == 0) {
            return false;
        }
        $inserts = array_map(function ($roleId) use ($administratorId) {
            return [
                'administrator_id' => $administratorId,
                'role_id' => $roleId,
            ];
        }, $rolesId);
        $rt = \App\Model\AdministratorRole::insert($inserts);
        if (! $rt) {
            throw new \Exception('设置角色失败');
        }
        return [];
    }

    /**
     * 更新 Administrator.
     * @throws \Exception
     * @return null|\Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|object
     */
    public static function updateAdministratorById(array $data)
    {
        try {
            $id = $data['id']??0;
            if ($id<=0){
                throw new \Exception('请选择管理员');
            }
            $administrator = \App\Model\Administrator::query()->find($id);
            if (! $administrator) {
                throw new \Exception('未找到数据');
            }

            if (isset($data['email']) && trim($data['email']) != '') {
                // 查找 email 是否已被其他人员暂用
                $emailAdmin = \App\Model\Administrator::query()->where('email', $data['email'])->where('id', '!=', $id)->first();
                if ($emailAdmin) {
                    throw new \Exception('此邮箱已被其他管理员占用, 请更换其他邮箱');
                }
            }
            Db::beginTransaction();
            $administrator->update($data);

            if (isset($data['roles_id'])) {
                self::setAdminRole($id, $data['roles_id']);
            }
            Db::commit();
            $administrator->roles;
            return  $administrator;
        } catch (\Throwable $exception) {
            Db::rollBack();
            throw new \Exception($exception->getMessage());
        }
    }
}